package com.iflytek.controller;

import com.iflytek.entity.Menu;
import com.iflytek.query.MenuQuery;
import com.iflytek.service.MenuService;
import com.iflytek.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("back/menu")
public class MenuController {

    @Autowired
    private MenuService menuService;

    @GetMapping("/list")
    public String list(){
        return "/menu/list";
    }


    @ResponseBody
    @GetMapping("listData")
    public List<Menu> listData(MenuQuery query){

        //查询数据列表
        List<Menu> menus = menuService.getMenuList(query);

        //返回分页数据
        return menus;

    }


    @GetMapping("edit")
    public String editUI(Integer menuId, Model model){
        Menu menu = menuService.getMenuById(menuId);
        //查询上级菜单
        MenuQuery query = new MenuQuery();
        query.setExcloudCode(menu.getCode());
        List<Menu> parentMenus = menuService.getMenuList(query);
        model.addAttribute("menu",menu);
        model.addAttribute("parentMenus",menu);
        return "menu/edit";
    }

    @ResponseBody
    @PostMapping("edit")
    public Map<String,Object> edit(Menu menu){
        if (menu == null || menu.getId() == null){
            return Result.failure("编辑失败");
        }
        int num = menuService.updateMenu(menu);
        if(num == 1){
            return Result.success("编辑成功");
        }
        return Result.failure("编辑失败");
    }

    @ResponseBody
    @PostMapping("delete")
    public Map<String,Object> delete(Integer menuId){
        if (menuId == null){
            return Result.failure("删除失败");
        }
        int num = menuService.deleteById(menuId);
        if(num == 1){
            return Result.success("删除成功");
        }
        return Result.failure("删除失败");
    }


}
